package se19team1e.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;

/**
 * 
 * Helper methods to setup and clean up when doing testing that involves DAO.
 * 
 * <p>
 * The helper methods will mainly copy the backup files from the ./data/bk to ./data/, at both before and after a test case.
 * </p>
 * 
 * @author lai shiaw san
 *
 */
public class DAOTestHelper {

    /**
     * This will copy the backup properties files from the ./data/bk to ./data/, at both before and after a test case.
     * @throws IOException Error with copying file.
     */
    public static void revertToBackupData() throws IOException {
        // copy all properties files from the ./data/bk to ./data/
        File dataFolder = new File( "./data" );
        File backupFolder = new File( dataFolder, "bk" );
        
        // list all properties file
        for ( File f : backupFolder.listFiles( new FilenameFilter() {
            @Override
            public boolean accept( File directory, String name ) {
                // only accept if its a file and is a properties file.
                return ( new File( directory, name ) ).isFile() && 
                    name.endsWith( ".properties" );
            }
        } ) ) {
            
            // copy over!
            copyFile( f, new File( dataFolder, f.getName() ) );
        }
    }

    /**
     * Copy file from source to destination.
     * @param src Source file to copy from.
     * @param dest Destination file to copy to.
     * @throws IOException Error with copying file.
     */
    private static void copyFile( File src, File dest ) throws IOException {
        FileInputStream input = new FileInputStream( src );
        try {
            FileOutputStream output = new FileOutputStream( dest );
            try {
                while ( input.available() > 0 ) {
                    int c = input.read();
                    output.write( c );
                }
                output.flush();
            } finally {
                output.close();
            }
        } finally {
            input.close();
        }
    }

}
